var express = require('express');
const userModel = require('../database/models/userModel');
var router = express.Router();
var bcrypt = require('bcryptjs')
var salt = bcrypt.genSaltSync(10)  //盐，加密强度
var jwt = require('jsonwebtoken')
var secret = 'asdfasdfasdfasdf3234lkjlalskdjfla'  //token签发的密钥

//注册接口
router.post('/', async function(req, res, next) {
  // 1. 拿到req.body中的账号密码
  let username = req.body.username
  let password = req.body.password

  // 2. 判断用户名是否可用，通过查询用户表去判断
  let result = await userModel.find({"username":username})
  console.log(result);
  if(result.length!=0){
    res.send({
      code:0,
      msg:'账号已被占用'
    })
    return
  }
  // 3. 密码加密
  let hash = bcrypt.hashSync(password,salt) 

  // 4. 账号录入数据库
  let addResult = await new userModel({
    "username":username,
    "password":hash
  }).save()
  if(addResult._id){
    res.send({
      code:1,
      msg:'注册成功'
    })
  }
});

// 登录
router.get('/', async function(req, res, next) {
  // 1. 获取客户端提交的账号+明文密码
  let {username,password} = req.query  //解构赋值

  // 2. 判断账号是否存在，账号查询(拿到加密的hash密码)
  let result = await userModel.find({"username":username})
  if(result.length==0){
    res.send({
      code:0,
      msg:'账号不存在'
    })
    return
  }

  // 3. 做密码比对 【明文密码】vs【hash密码】
  let hash = result[0].password //提取数据库查出来的hash密码
  let bool = bcrypt.compareSync(password,hash) //密码比对
  if(!bool){
    res.send({
      code:0,
      msg:'密码错误'
    })
    return
  }
  // 4. 签发token
  let token = jwt.sign({
    time:Date.now(),  //签发时间戳
    expire:1000*60*30  //有效时长
  },secret)
  console.log('令牌',token);
  res.send({
    code:1,
    msg:'登录成功',
    data:{
      token,
      username
    }
  })
  

});

// token认证接口
router.get('/auth',(req,res)=>{
  let {token} = req.query
  // 1. 合法性判断
  jwt.verify(token, secret, function(err, decoded) {
    console.log(decoded.foo) // bar
    if(err){
      res.send({
        code:0,
        msg:'非法token，请登录'
      })
      return
    }
    // 2. 有效性判断
    let {time,expire} = decoded  //从合法token中解析出签发事件、有效时长
    let now = Date.now()
    if(now-time>expire){
      res.send({
        code:0,
        msg:'token已过期，请重新登录'
      })
      return
    } 
    // 3. 通过认证
    res.send({
      code:1,
      msg:'登录状态正常'
    })
  });
  
})
module.exports = router;
